<template>
    <el-dialog
        :visible="true"
        width="640px"
        :fullscreen="fullScreen"
        :append-to-body="true"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :before-close="handleClose">
        <span slot="title" class="el-dialog__title">
            批量导入
            <i class="el-icon-full-screen iconClass" v-if="!fullScreen" @click="()=>{fullScreen = true}"></i>
            <i class="el-icon-aim iconClass" v-else @click="()=>{fullScreen = false}"></i>
        </span>
        <div class="dialogBody">
            <div v-if="active === 0" v-loading="uploadLoading">
                <div style="margin-top: 10px;">
                    <div style="font-weight:600;display:inline-block">· 上传的EXCEL文件需符合以下规范:<span @click="downloadTemp()" class="downLoadCss">下载模板</span></div><br>
                    <div style="margin: 10px 0px 0px 5px">
                        <span>导入数据 : </span>
                        <el-select v-model="updateDataType" placeholder="请选择" style="width: 200px">
                            <el-option
                            v-for="item in updateOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="spanClass">· 不能存在合并的单元格;</div><br>
                    <div class="spanClass">· 文件大小不超过10MB;</div><br>
                    <div class="spanClass">· 仅支持（*.xls和*.xlsx）文件;</div><br>
                    <div class="spanClass">· 文本不能超过1000行、200列;</div><br>
                    <div class="spanClass">· 请确保按模板导入您的数据，否则可能导入失败或错误;</div><br>
                    <!-- <div class="spanClass">· 请确保您需要导入的Sheet表头中不包含空的单元格，否则该Sheet页数据系统将不做导入;</div><br>
                    <div class="spanClass">· 导入只做简单的数据类型以及必填校验，不做数据有效性校验，请自行确保导入数据的正确性;</div><br>
                    <div class="spanClass">· 导入的Excel表单字段与表单字段名保持一致，注意检查空格、字符等。</div><br> -->
                </div>
                <div>
                    <el-upload
                        ref="uploadRef"
                        class="upload-demo"
                        drag
                        accept=".xls, .xlsx"
                        :before-upload="beforeUpload"
                        :file-list="fileList"
                        :on-remove="deleteFile"
                        :on-error="uploadError"
                        :on-exceed="exceedLimit"
                        :on-change="uploadChange"
                        :limit="1"
                        :auto-upload="false"
                        action="name"
                        :http-request="httpRequest"
                        :show-file-list="true">
                        <el-button icon="el-icon-upload">选择或拖拽上传文件，10MB以内</el-button>
                    </el-upload>
                </div>
                <div class="dialog-footer">
                    <el-button @click="handleClose(false)" size="small">取消</el-button>
                    <el-button @click="startUpload" size="small" type="primary">开始上传</el-button>
                </div>
            </div>
            <div v-else>
                <div v-if="errorLength > 0">
                    <div class="middleBody">
                        <div class="tipClass">
                            <i class="el-icon-warning"> 错误提醒：导入数据失败展示</i>
                        </div>
                        <span class="errorTipClass">
                            <img :src="tipPng" style="float:left">
                            <div class="tipTextClass">
                                <span class="textClass">正常数量条数：</span><span class="greenClass">{{correctLength}} 条</span><br>
                                <span class="textClass">异常数量条数：</span><span class="redClass">{{errorLength}} 条</span>
                            </div>
                        </span>
                    </div>
                    <div style="margin: 10px 0px;">
                        <span>以下数据为导入异常数据</span>
                        <i class="el-icon-download exportTip" @click="exportExceptionData"> 导出异常数据</i>
                    </div>
                    <div>
                        <el-table highlight-current-row height="270" border style="width: 100%"
                        :data="failTableList.slice((pageNo - 1) * pageSize, pageNo * pageSize)">
                            <el-table-column show-overflow-tooltip prop="errorLine" label="错误行数" :key="0"></el-table-column>
                            <el-table-column v-for="(field, index) in tableFieldList" :key="index + 1" show-overflow-tooltip :prop="field.propName" >
                                <template slot="header">
                                    <div :title="field.comment" class="headerCss">{{field.comment}}</div>
                                </template>
                            </el-table-column>
                            <el-table-column show-overflow-tooltip prop="errorMsg" label="异常原因"></el-table-column>
                        </el-table>
                    </div>
                    <div style="display: flow-root;margin-top: 10px;">
                        <el-pagination background :layout="layout" :total="failTableList.length" :page-sizes="pageSizes"
                            :current-page="pageNo" :page-size="pageSize" style="float:right;"
                            @size-change="configSizeChange" @current-change="configCurrentChange">
                        </el-pagination>
                    </div>
                </div>
                <div v-else>
                    <el-result style="height:510px" icon="success" title="批量导入成功" :subTitle="'您已成功导入'+ correctLength + '条数据'"></el-result>
                </div>
                <div style="margin-top:35px;float:right">
                    <el-button @click="handleClose(true)" size="small" type="primary">关闭</el-button>
                </div>
            </div>
        </div>
    </el-dialog>
</template>
<script>
import tipPng from '@/assets/images/dengpao.png'
import {inputComponents, selectComponents} from '../../../../components/generator/config.js'
import {deepClone} from '../../../../utils/index.js'
import XLSX from '@/utils/xlsx.core.min.js'
export default {
    name: 'TableDataImportDialog',
    data () {
        return {
            layout: 'prev, pager, next,sizes,jumper', //分页显示布局
            pageSizes: [10, 20, 30, 50], //分页显示每页条数选择
            tipPng:tipPng,
            inputComponents: inputComponents,
            selectComponents: selectComponents,
            active: 0,
            fullScreen: false,
            fileList: [],
            sheetValue: '',
            failTableList: [],
            sheetMap: new Map(),
            curSheetList: [],
            localStorageTemp: '',
            tenantId: '',
            tableName: 'table1371',
            api: '', //接口请求base_api
            uploadLoading: false, // 遮罩层
            tableFieldList: [],
            tablePropList: [],
            pageNo: 1,
            pageSize: 10,
            sucessList: [], // 子表单导入数据使用
            correctLength: 0, // 正确条数
            errorLength: 0, // 错误条数
            updateDataType: 'add',
            updateOptions: [
                {
                    label: '仅新增数据',
                    value: 'add'
                },
                // {
                //     label: '仅更新数据',
                //     value: 'update'
                // },
            ]
        }
    },
    props: ['curFormName', 'curFormId', 'tableFlag'],
    created () {
        this.localStorageTemp = window.localStorage.getItem('ACCESS_TOKEN');
        this.tenantId = window.localStorage.getItem('TENANT_ID')
        this.api = process.env.VUE_APP_BASE_API
    },
    methods: {
        httpRequest(option) {
            this.fileList.push(option)
        },
        configSizeChange (size) {
            this.pageSize = size
        },
        configCurrentChange (page) {
            this.pageNo = page
        },
        exceedLimit (files, fileList) {
            return this.$message.warning('最多上传一个文件')
        },
        uploadError (err, file, fileList) {
            return this.$message.warning(err)
        },
        deleteFile () {
            this.fileList.splice(0, 1)
        },
        // 开始上传
        startUpload () {
            if (this.fileList.length === 0) {
                return this.$message.warning('请先上传文件')
            }
            this.uploadLoading = true
            // this.$refs.uploadRef.submit();
            console.log('api', this.api)
            // const url = `${this.api}/admin-api/form/project/excelImportData`
            const obj = {}
            const params = new FormData()
            // 将上传文件数组依次添加到参数paramsData中
            this.fileList.forEach((x) => {
                params.append('file', x.raw)
                params.append('updateType', this.updateDataType)
                obj.file = x.raw
            });
            // 将输入表单数据添加到params表单中
            params.append('tableName', this.curFormId)
            const header = { 'Authorization': 'Bearer ' + this.localStorageTemp, 'tenant-id': window.localStorage.getItem('TENANT_ID')}
            let importUrl = this.tableFlag === 'Subform' ? '/form/project/excelInputChildForm' : '/form/project/excelImportData';
            this.$axios.post(importUrl, params, { headers: header }).then(response => {
                if (response.code === 0) {
                    if(this.tableFlag === 'Subform'){
                        if(response.data.length > 0){
                            response.data.forEach(info=>{
                                if(info.sysFromDataColumnVoList?.length > 0){
                                    let obj = {showComp:true}
                                    info.sysFromDataColumnVoList.forEach((item, index) => {
                                        obj[item.name] = item.value;
                                    })
                                    this.sucessList.push(obj)
                                }
                            })
                        }
                        this.correctLength = this.sucessList.length;
                    }else{
                        if (response.data === false || response.data === null) {
                    this.uploadLoading = false
                    return this.$message.error(response.msg)
                  }
                  this.correctLength = response.data.sucesNumver
                  this.errorLength = response.data.erroNumber
                  if (response.data.failedList.length > 0) {
                      response.data.failedList[0].data.forEach(item => {
                        let obj = {}
                        obj.comment = item.comment
                        obj.propName = item.name
                        this.tableFieldList.push(obj)
                      })
                      response.data.failedList.forEach((item, index) => {
                        let obj = {}
                        item.data.forEach(field => {
                          // obj.label = field.comment  // 组件名称: 例 下拉框组
                          // obj.field = field.name  // 字段名 field101
                          obj[field.name] = field.value // 字段值
                        })
                        obj.errorMsg = item.failure
                        obj.errorLine = item.rowNumber
                        this.failTableList.push(obj)
                      })
                  }
                  if (response.data?.sucessList?.length > 0) {
                    response.data.sucessList.forEach((item, index) => {
                      let obj = {}
                      item.data.forEach(field => {
                          obj.showComp = true
                          obj[field.name] = field.value // 字段值
                      })
                      this.sucessList.push(obj)
                    })
                  }
                    }
                    this.fileList = []
                    this.active = 1
                }else{
                    this.$message.error(response.data)
                }
                this.uploadLoading = false
            }).catch(e => {
                this.uploadLoading = false
            })
        },
        uploadChange (file, fileList) {
            this.fileList = [...fileList]
        },
        // 上传前钩子判断
        beforeUpload (file) {
            const size = file.size / 1024 / 1024
            if (size > 10) {
                this.$message.warning('文件最大不超过10M')
                return false
            }
            const nameLst = file.name.split('.')
            const type = nameLst[nameLst.length - 1]
            if (!['xls', 'xlsx'].includes(type)) {
                this.$message.warning('文件只支持xls,xlsx格式')
                return false
            }
        },
        // 关闭弹框
        handleClose (flag) {
            let obj = {}
            obj = {flag: flag}
            if (this.tableFlag === 'Subform') {
                obj.data = this.sucessList
            }
            this.$emit('closeDialog', obj)
        },
        // 导出异常数据
        exportExceptionData () {
            const header = {}
            let cols = []
            header.errorLine = '错误行数'
            cols.push({wch: 15})
            this.tableFieldList.forEach(table => {
                cols.push({
                    wch: 30
                })
                header[table.propName] = table.comment
            })
            header['errorMsg'] = '异常原因'
            cols.push({wch: 30})
            // 新建空workbook，然后加入worksheet
            const ws = XLSX.utils.json_to_sheet([header, ...this.failTableList], {
                skipHeader: true
            })
            // 设置每列的列宽，10代表10个字符，注意中文占2个字符
            ws['!cols'] = cols
            // 新建book
            const wb = XLSX.utils.book_new()
            // 生成xlsx文件(book,sheet数据,sheet命名)
            XLSX.utils.book_append_sheet(wb, ws, this.curFormName)
            // 写文件(book,xlsx文件名称)
            XLSX.writeFile(wb, `${this.curFormName}.xlsx`)
        },
        //下载模板
        downloadTemp() {
            const req = new XMLHttpRequest()
            req.open('GET', `${this.api}/admin-api/form/project/get-import-template?tableName=${this.curFormId}`, true)
            req.responseType = 'blob'
            req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
            req.setRequestHeader('Authorization', `Bearer ${this.localStorageTemp}`)
            let _this = this
            req.onload = function () {
                let blob = this.response
                const url = window.URL.createObjectURL(blob)
                let link = document.createElement("a");
                link.href = url;
                link.download = decodeURI(`${_this.curFormName}.xlsx`); //这里是最后下载下来的excel表格名称
                document.body.appendChild(link)
                link.click();
                window.URL.revokeObjectURL(url)
                document.body.removeChild(link)
            }
            req.send()
        },
    }
}
</script>
<style lang="less" scoped>
/deep/.el-dialog__title{
    width: 100%;
}
.headerCss{
    white-space:nowrap; // 禁止文字换行
    text-overflow: ellipsis;  // 过长显示省略号
    overflow: hidden;  // 溢出内容为隐藏
}
.exportTip{
    float: right;
    color: #409EFF;
    cursor: pointer;
}
.greenClass{
    color: green;
}
.redClass{
    color: red;
}
.textClass{
    font-size: 14px;
}
.tipTextClass{
    display: inline-block;
    line-height: 30px;
    margin: 25px;
}
.errorTipClass{
    display: inline-block;
    width: 100%;
    height: 115px;
    border: 1px solid lightgrey;
    margin-top: 20px;
}
.tipClass{
    background-color: oldlace;
    color: orange;
    height: 28px;
    line-height: 28px;
    padding-left: 10px;
    font-size: 12px;
}
.downLoadCss{
    color: #409EFF;
    font-size: 12px;
    display: inline-block;
    padding-left: 20px;
    cursor: pointer;
}
.dialog-footer{
    float: right;
    margin-top:50px;
}
.middleBody{
    padding: 20px 0px;
}
/deep/.el-input--medium .el-input__inner {
    height: 28px;
    line-height: 28px;
}
/deep/.el-input--medium .el-input__icon {
    height: 28px;
    line-height: 28px;
}
/deep/.el-upload-dragger .el-icon-upload {
    font-size: 15px;
    margin: 0px;
    line-height: 40px;
}
/deep/.el-button--medium {
    padding: 0px 20px;
    margin-top: 100px;
}
.spanClass{
    font-size: 12px;
    display: inline-block;
    padding: 8px 0px;
}
.iconClass{
    float:right;
    margin-right:25px;
    line-height: 1.5;
}
/deep/.el-upload-dragger{
    width: 100% !important;
    height: 220px;
}
/deep/.el-upload {
    width: 100%;
}
/deep/.el-dialog__body{
    height: 640px;
    padding: 0px 20px;
}
/deep/::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 5px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 5px;
}
/deep/::-webkit-scrollbar-thumb {
  background-color: skyblue;
  background-image: -webkit-linear-gradient(
    45deg,
    rgba(255, 255, 255, 0.2) 25%,
    transparent 25%,
    transparent 50%,
    rgba(255, 255, 255, 0.2) 50%,
    rgba(255, 255, 255, 0.2) 75%,
    transparent 75%,
    transparent
  );
  /*滚动条里面小方块*/
  border-radius: 10px;
}
/deep/::-webkit-scrollbar-track {
  background: #ededed;
  border-radius: 10px;
  /*滚动条里面轨道*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
}
</style>